#include <stdio.h>
#include "../include/data_hand.h"

/* 链表实现函数 包括创建,插入，删除，显示 */
linkhead_t *create_linklist(void)
{
    linkhead_t *l = (linkhead_t *)malloc(sizeof(linkhead_t));
    l->len = 0;  //　对于头结点的数据域可以指定为该链表中有效节点的个数
    l->next = NULL; 
    return l;
}
int is_empty_link(linkhead_t *l)
{
    return (l->next == NULL);

}
int insert_linklist(int pos, struct env_info data, linkhead_t *l)
{

    if(pos < 0 || (pos > l->len))
    {
        puts("insert error,the position is wrong!");
        return -1;
    }
    linknode_t *node =(linknode_t *)malloc(sizeof(linknode_t));
    node->data = data;
    node->next = NULL;

    linknode_t *q = l->next;

    if(q == NULL)
    {
        l->next = node;
        l->len ++;
        return 0;
    }

    if(pos == 0)
    {
        l->next = node;
        node->next = q;
        l->len ++;
        return 0;
    }

    int i = 1;

    while(i < pos)
    {
        q = q->next;
        i ++;
    }
    node->next = q->next;
    q->next = node;
    l->len ++;
    return 0; 
}


struct env_info *delete_linklist(int pos, linkhead_t *l)
{
    if(is_empty_link(l))
    {
        puts("delete error!the linklist is empty");
        return NULL;
    }
    if(pos < 0 || (pos > l->len))
    {
        puts("the position is error!");
        return NULL;
    }

    linknode_t *p = l->next;
    linknode_t *del = NULL;
    struct env_info *del_val = NULL;
    del_val = (struct env_info *)malloc(sizeof(struct env_info));

    if(pos == 0)
    {
        del = p;
        *del_val = del->data;
        l->next = del->next;
        free(del);
        del = NULL;

        l->len--; //头结点的len 要-1
        return del_val;
    }

    int i = 1;
    while(i < pos)
    {
        p = p->next;
        i ++;
    }

    del = p->next;
    *del_val = del->data;

    p->next = del->next;

    free(del); //释放要删除的节点
    del = NULL; 
    l->len--; //头结点的len 要减一
    return del_val; //返回删除的值

}

int show_linklist(linkhead_t *l)
{
    /*
    static int i = 0;
    i ++;

    printf("showlink : %d\n", i);
    */
    if(is_empty_link(l))
    {
        puts("show error,the linklist is empty!");
        return -1;
    }

    linknode_t *p = l->next;

    puts("---------------------------------");
    printf("head->");
    while(p != NULL)
    {
        printf("--%d ",p->data.x);
        p = p->next;
    }
    /*
    while(j < l->len)
    {
        printf("--%d ",p->data.x);
        p = p->next;
        j ++;

    }
    */
    printf("\n");
    puts("-------xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
    return 0;

}

int clear_link(linkhead_t *l)
{
    if(is_empty_link(l))
    {
        puts("clear error,the linklist is empty!");
        return -1;
    }
    linknode_t *pre, *p;
    pre = l->next;
    p = pre->next;

    while(p != NULL)
    {
        free(pre);
        pre = p;
        p = p->next;
    }

    free(pre);
    l->len = 0;
    l->next = NULL;

    return 0;

}





